package com.sllp.C71S3TsllpShop.web;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.sllp.C71S3TsllpShop.bean.Result;
import com.sllp.C71S3TsllpShop.bean.User;
import com.sllp.C71S3TsllpShop.bean.VerifyCode;
import com.sllp.C71S3TsllpShop.biz.impl.UserBizImpl;
import com.sllp.C71S3TsllpShop.util.AddCookie;
import com.sllp.C71S3TsllpShop.util.RandomUtils;
import com.sllp.C71S3TsllpShop.util.SendEmail;
import com.sllp.C71S3TsllpShop.util.VerificationCodeGeneratorUtil;

@Controller
@SessionAttributes({"loginUser","resetPwdEmailCode"})
public class LoginAction {

	@Resource
	private UserBizImpl ub;
	@Resource
	private AddCookie addCookie;
	
	@GetMapping("toLogin.do")
	public String toLogin(HttpSession httpSession,Model m,HttpServletRequest request,HttpServletResponse response) {
		// 判断是否为第一次进入此页面，为了实现记住密码
		int landed = 0;
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals("name")) {
				landed++;
				continue;
			}else if(cookie.getName().equals("pwd")) {
				landed++;
				continue;
			}
		}
		if(landed != 2) {
			Cookie cname = new Cookie("name","" );
		    Cookie cpwd = new Cookie("pwd", "");
		    response.addCookie(cname);
		    response.addCookie(cpwd);
		}
		m.addAttribute("result", new Result(1));
		return "Login";
	}
	
	/**
	 * 点击登录按钮后的操作
	 * @param user  用户
	 * @param loginVerifyCode  用户输入的验证码
	 * @param remPwd  是否记住密码
	 * @param m
	 * @param code  系统生成的验证码
	 * @return
	 */
	@PostMapping("loginNow.do")
	public String toLoginNow(User user,String loginVerifyCode,boolean remPwd,Model m,@SessionAttribute("VerifyCode") String code,HttpServletRequest request,HttpServletResponse response) {
		System.out.println(remPwd);
		if(!loginVerifyCode.equals(code)) {
			m.addAttribute("result", new Result(0, "验证码错误"));
			return "Login";
		}
		Result result = ub.userLogin(user);
		if(result.getSucess()==0) {
			m.addAttribute("result", result);
			return "Login";
		}
		User user1= (User)result.getObj();
		// 登录成功后
		// 添加Cookie
		addCookie.addCookie(false, remPwd, user1.getLoginName(), user1.getPwd(), request, response);
		m.addAttribute("loginUser", user1);
		return "redirect:/index";
	}
	
	@GetMapping("logVerifyCode.do")
	public void toLogVerifyCode(HttpServletRequest request, HttpServletResponse response) {
		VerificationCodeGeneratorUtil iVerifyCodeGen = new VerificationCodeGeneratorUtil();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
        	System.out.println(e.getMessage());
        }
	}
	
	@GetMapping("loginOut.do")
	public String outLogin(HttpSession session,Model m) {
		User user = (User) session.getAttribute("loginUser");
		if(user != null) {
			session.removeAttribute("loginUser");
		}
		return "redirect:/toLogin.do";
	}
	
	
	@Value("${mail.formMail.addr}")
	private String from;
	@Value("${mail.formMail.resetPwdEmailContent}")
	private String resetPwdEmailContent;
	@Resource
	private SendEmail sendEmail;
	
	@ResponseBody
	@PostMapping("sendResetPwdEmail.do")
	public Result sendResetPwdEmail(String userName,Model m) {
		System.out.println(userName);
		Result findUserEmailResult = ub.findUserEmail(userName);
		if(findUserEmailResult.getSucess()==0) {
			return findUserEmailResult;
		}
		User user = (User)findUserEmailResult.getObj();
		String resetPwdEmailCode = RandomUtils.randomString(4);
		m.addAttribute("resetPwdEmailCode", resetPwdEmailCode);
		Result result = sendEmail.sendEmail("尤洪商城", from, user.getEmail(), resetPwdEmailContent,resetPwdEmailCode);
		return result;
	}
	
	@ResponseBody
	@PostMapping("resetPWD.do")
	public Result resetPWD(User user,String resetEmailCode,String resetUserPwd,@SessionAttribute("resetPwdEmailCode")String resetPwdEmailCode) {
		if(resetPwdEmailCode.equals(resetUserPwd)) {
			return new Result(0	, "验证码错误");
		}
		user.setPwd(resetUserPwd);
		Result result = ub.updateUserPwd(user);
		return result;
	}
}
